package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private FriendsApi friendsApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //添加联系人
    public void addContacts(Long friendId) {
        //1、保存好友关系到MongoDB数据库中
        friendsApi.save(UserHolder.getUserId(),friendId);
        //2、注册好友关系到环信服务器
        huanXinTemplate.addContact("hx"+UserHolder.getUserId(),"hx"+friendId);
    }

    //查看好友列表
    public PageResult findContacts(int page, int pagesize) {
        //1、查询当前用户的好友列表（分页）  List<Friend>
        List<Friend> friends = friendsApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        //获取好友用户id
        List<Long> friendIdS = CollUtil.getFieldValues(friends, "friendId",
                Long.class);
        //2、根据用户好友的好友ID，查询所有好友的用户资料 List<UserInfo>
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIdS, null);
        //3、循环好友资料的列表，一个UserInfo构造一个ContractVo对象 List<ContractVo>
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : friends) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if(userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        //4、构造PageResult
        return new PageResult(page,pagesize,0l,vos);
    }

    //根据环信id。查询用户信息
    public UserInfoVo findByHuanxinId(String huanxinId) {
        //1、提取用户id
        String temp = huanxinId.replaceAll("HX", "");
        Long userId = Long.valueOf(temp);
        //2、根据用户id查询用户信息  UserInfo
        UserInfo userInfo = userInfoApi.findById(userId);
        //3、构造UserInfoVo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);
        if(userInfo.getAge()!= null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

}
